<template>
  <div>
    <div v-if="!look" class="w-100 d-flex j-start">
      <el-form :inline="true" class="demo-form-inline" size="small">
        <el-form-item label="">
          <el-input v-model="upLoadFileName" placeholder="请选择文件" disabled />
        </el-form-item>
        <el-form-item>
          <el-upload action="" :accept="type === 'file' ? '.pdf,.doc,.docx' : '.png, .jpg, .jpeg, .gif'" :before-upload="beforeUpload" :file-list.sync="fileLists" :show-file-list="false">
            <el-button slot="trigger" size="small" type="primary">浏览</el-button>
            <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload()">上传</el-button>
            <span class="redText">
              {{ type === 'file' ? fileText : imageText }}
            </span>
          </el-upload>
        </el-form-item>
        <el-form-item v-if="showProgress" label="上传进度：">
          <div style="width:200px;padding-top:7px">
            <el-progress :percentage="progressPercent" :status="progressStatus" />
          </div>
        </el-form-item>
      </el-form>
    </div>
    <!-- 列表 -->
    <el-table v-if="type === 'file'" class="mb-3" :data="upLoadFileList" style="width: 100%" border stripe size="mini" :header-cell-style="{ background: '#e9ecf4', color: '#606266' }">
      <el-table-column type="index" label="序号" align="center" />
      <el-table-column label="附件名称" align="center">
        <template slot-scope="scope">
          <b v-if="scope.row.attachFileName !== ''">{{ scope.row.attachFileName }}</b>

          <b v-else>{{ scope.row.attachName }}</b>
        </template>
      </el-table-column>

      <el-table-column v-if="!look" label="操作" align="center">
        <template slot-scope="scope">
          <!-- <el-link
            class="mr-2"
            type="success"
            :underline="false"
            icon="el-icon-view"
            @click="handleLook(scope.$index, scope.row)"
          >查看</el-link> -->
          <a :href="`${downloadFile}${scope.row.attachId}`"> <span icon="el-icon-view" /> 下载 </a>
          <el-link type="danger" :underline="false" icon="el-icon-delete" @click="handleRemove(scope.row)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>
    <!-- 图片 -->
    <div v-else class="image-warp">
      <template v-if="upLoadFileList.length !== 0">
        <div v-for="(file, index) in upLoadFileList" :key="index" class="image-item" @mouseenter="tools = true" @mouseleave="tools = false">
          <img :src="`${downloadFile}${file.attachId}`" alt="">
          <span v-if="tools" class="item-actions">
            <span @click="handlePictureCardPreview(`${downloadFile}${file.attachId}`)">
              <i class="el-icon-zoom-in" />
            </span>
            <a :href="`${downloadFile}${file.attachId}`">
              <i class="el-icon-download" />
            </a>
            <span v-if="!look" @click="handleRemove(file)">
              <i class="el-icon-delete" />
            </span>
          </span>
        </div>
      </template>
      <template v-else>
        <div class="image-nodata">暂无数据</div>
      </template>
    </div>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { deleteAttachment } from '@/api/common'
export default {
  props: {
    type: {
      type: String,
      default: 'file' // file 文件   images  图片
    },
    look: {
      type: Boolean,
      default: false
    },
    list: {
      type: Array,
      default() {
        return []
      }
    },
    filtType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      tools: false,
      fileText: '注：附件类型为 doc、docx、xls、xlsx、pdf 文件，大小不得超过50M',
      imageText: '注：附件类型为 jpg、png、jpeg、gif 文件，且不超过500kb',
      fileLists: [],
      fileType: 'doc、docx、xls、xlsx、pdf',
      imageType: 'jpg、png、jpeg、gif',
      upLoadFileName: '',
      actionUrl: `${process.env.VUE_APP_BASE_API}/admin/attachment/addAttachment.do`,
      progressPercent: 0,
      showProgress: false,
      progressStatus: 'warning',
      upLoadFileList: [],
      downloadFile: `/XinJiGuFei/admin/attachment/downloadAttachment.do?attachId=`,
      dialogVisible: false,
      dialogImageUrl: ''
    }
  },
  methods: {
    // 选择附件
    beforeUpload(newFile) {
      console.log(newFile)
      let state, size
      var testmsg = newFile.name.substring(newFile.name.lastIndexOf('.') + 1)
      console.log(testmsg)
      if (this.type === 'file') {
        state = this.fileType.indexOf(testmsg) > -1
        if (!state) {
          this.$message({
            message: '上传文件只能是 doc、docx、xls、xlsx、pdf格式！',
            type: 'warning'
          })
          return false
        }
        size = newFile.size / 1024 / 1024 < 50
        if (!size) {
          this.$message({
            message: '上传文件大小不能超过 50MB！',
            type: 'warning'
          })
          return false
        }
      } else if (this.type === 'images') {
        state = this.imageType.indexOf(testmsg) > -1
        if (!state) {
          this.$message({
            message: '上传文件只能是 jpg、png、jpeg、gif格式！',
            type: 'warning'
          })
          return false
        }
        size = newFile.size / 1024 / 1024 < 5
        if (!size) {
          this.$message({
            message: '上传文件大小不能超过 500k！',
            type: 'warning'
          })
          return false
        }
      }

      this.fileLists = []
      this.progressPercent = 0
      this.showProgress = true
      this.progressStatus = 'warning'
      this.fileLists.push({
        name: newFile.name,
        url: '',
        file: newFile,
        status: 'ready',
        percentage: 0
      })
      this.upLoadFileName = newFile.name
      return false
    },
    // 上传附件
    submitUpload() {
      let readyFile = null
      if (this.fileLists.length === 0) {
        return this.$message({
          message: '请选择文件',
          type: 'warning'
        })
      } else {
        for (const file of this.fileLists) {
          if (file.status === 'uploading') {
            return this.$message.error('已有文件正在上传')
          }
          if (file.status === 'ready') {
            readyFile = file
          }
        }
      }

      const formdata = new FormData()
      formdata.append('file', readyFile.file)
      formdata.append('attachName', readyFile.name)
      const config = {
        onUploadProgress: (progressEvent) => {
          // progressEvent.loaded:已上传文件大小
          // progressEvent.total:被上传文件的总大小
          this.progressPercent = Number(((progressEvent.loaded / progressEvent.total) * 100).toFixed(2))
        }
      }
      this.$axios.post(this.actionUrl, formdata, config).then((res) => {
        const result = res.data
        if (result.status === 0 && result.data) {
          this.$message({
            message: '上传成功',
            type: 'success'
          })
          this.upLoadFileName = ''
          this.fileLists = []
          this.progressStatus = 'success'
          this.upLoadFileList.push(result.data)
          this.$emit('uploadCallbck', result.data)
          setTimeout(() => {
            this.showProgress = false
          }, 3000)
        } else {
          this.$message({
            message: result.msg,
            type: 'error'
          })
          this.progressStatus = 'exception'
          setTimeout(() => {
            this.showProgress = false
          }, 3000)
        }
      })
    },
    // 预览附件
    handlePictureCardPreview(url) {
      this.dialogImageUrl = url
      this.dialogVisible = true
    },
    // 删除附件
    handleRemove(file) {
      const { attachId } = file
      const index = this.upLoadFileList.findIndex((v) => {
        return v.attachId === attachId
      })
      this.deleteFile(attachId, index)
    },
    async deleteFile(attachId, index) {
      const { status, msg } = await deleteAttachment({ attachId })
      if (status === 0) {
        this.$message({
          message: msg,
          type: 'success'
        })
        this.$emit('deleteCallbck', attachId)
        this.upLoadFileList.splice(index, 1)
      } else {
        this.$message({
          message: msg,
          type: 'warning'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.image-warp {
  display: flex;
  flex-wrap: wrap;
  .image-item {
    width: 200px;
    height: 200px;
    margin-right: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    overflow: hidden;

    img {
      width: 100%;
      height: auto;
    }
    .item-actions {
      width: 100%;
      height: 100%;
      position: absolute;
      z-index: 1500;
      top: 0;
      left: 0;
      display: -webkit-box;
      display: -ms-flexbox;
      display: flex;
      -webkit-box-align: center;
      -ms-flex-align: center;
      align-items: center;
      -ms-flex-pack: distribute;
      justify-content: space-around;
      background: #00000052;
      i {
        cursor: pointer;
        font-size: 20px;
        color: #ffffff;
      }
    }
  }
  .image-nodata {
    width: 50%;
    margin: 0 auto;
    line-height: 60px;
    font-size: 12px;
    color: #909399;
    text-align: center;
  }
}
</style>
